<template>
  <div>
    <v-card class="full-width-card">
      <v-card-title>通知公告管理</v-card-title>
      <v-card-text>
        <v-row class="mb-4" align="center" no-gutters>
          <v-col cols="12" sm="4" md="3">
            <v-text-field
              v-model="searchTitle"
              label="标题搜索"
              clearable
              density="comfortable"
              variant="outlined"
              hide-details
              @keyup.enter="onSearch"
            />
          </v-col>
          <v-col cols="12" sm="4" md="3">
            <v-select
              v-model="searchStatus"
              :items="statusOptions"
              label="状态"
              clearable
              density="comfortable"
              variant="outlined"
              hide-details
            />
          </v-col>
          <v-col cols="12" sm="4" md="5" class="d-flex justify-end align-center gap-btns">
            <v-btn
              variant="outlined"
              color="grey-darken-1"
              elevation="0"
              rounded
              @click="onSearch"
              size="large"
              class="mr-2"
              style="height: 40px; min-width: 90px; background: rgba(128,128,128,0.08);"
            >
              搜索
            </v-btn>
            <v-btn
              variant="outlined"
              color="grey-darken-1"
              elevation="0"
              rounded
              @click="onAddNotice"
              size="large"
              style="height: 40px; min-width: 90px; background: rgba(128,128,128,0.08);"
            >
              新增
            </v-btn>
          </v-col>
        </v-row>
        <v-table>
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>内容</th>
              <th>状态</th>
              <th>创建时间</th>
              <th  style="text-align: center">操作</th>
              <th>创建人</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="notice in notices" :key="notice.id">
              <td>{{ notice.id }}</td>
              <td>{{ notice.title }}</td>
              <td>{{ notice.content }}</td>
              <td>{{ notice.status === 1 ? '启用' : '停用' }}</td>
              <td>{{ notice.create_time }}</td>
              <td style="text-align: center">
               <v-btn size="small" variant="text" color="info" @click="onEditNotice(notice)">编辑</v-btn>
                <v-btn size="small" variant="text" color="error" @click="onDeleteNotice(notice)">删除</v-btn>
              </td>
              <td>{{ notice.username }}</td>
            </tr>
          </tbody>
        </v-table>
        <div class="d-flex justify-space-between align-center mt-4">
          <span>本页共 {{ notices.length }} 条</span>
          <div class="d-flex align-center">
            <span style="margin-right: 12px;">第{{ page }}页 / 共{{ pageCount }}页</span>
            <v-pagination v-model="page" :length="pageCount" @input="onPageChange" />
          </div>
        </div>
      </v-card-text>
    </v-card>
    <v-dialog v-model="dialog" max-width="600px" persistent>
      <v-card>
        <v-card-title>{{ dialogMode === 'add' ? '新增公告' : '编辑公告' }}</v-card-title>
        <v-card-text>
          <v-form ref="formRef">
            <v-text-field v-model="dialogNotice.title" label="标题" required />
            <v-textarea v-model="dialogNotice.content" label="内容" required rows="4" />
            <v-select v-model="dialogNotice.status" :items="statusOptions.filter(i => i.value !== null)" label="状态" required />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeDialog">关闭</v-btn>
          <v-btn color="primary" @click="onSaveNotice">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getNoticeList, createNotice, updateNotice } from '@/api/auth'
import {getUserTree} from "@/api/user.js";

const notices = ref([])
const users = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const searchTitle = ref('')
const searchStatus = ref(null)
const statusOptions = [
  { title: '全部', value: null },
  { title: '启用', value: 1 },
  { title: '停用', value: 0 },
]

const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

const dialog = ref(false)
const dialogMode = ref('add')
const dialogNotice = ref({})
const formRef = ref(null)

function fetchData() {
  const params = {
    pageNum: page.value,
    pageSize: pageSize.value,
    title: searchTitle.value,
  }
  const userP = {
    pageNum: 1,
    pageSize: 9999,
  }
  if (searchStatus.value !== null && searchStatus.value !== undefined && searchStatus.value !== '') {
    params.status = searchStatus.value
  }
  getNoticeList(params).then(res => {
    notices.value = res.data.list || []
    total.value = res.data.total || 0
    getUserTree(userP)
      .then(res => {

        users.value = res.data.list || []
        total.value = res.data.total || 0
        const userMap = new Map();
        users.value.forEach(user => {
          userMap.set(user.id, user.username);
        });
        console.log(notices.value)
        console.log(userMap)
        notices.value = notices.value.map(notice => {
          return {
            ...notice,
            username: userMap.get(notice.user_id) || '未知用户' // 添加username字段
          };
        });

        console.log('处理后的通知列表:', notices.value);
      })
  })


}

function onPageChange(val) {
  page.value = val
  fetchData()
}

function onSearch() {
  page.value = 1
  fetchData()
}

function onAddNotice() {
  dialogMode.value = 'add'
  dialogNotice.value = { title: '', content: '', status: 1 }
  dialog.value = true
}

function closeDialog() {
  dialog.value = false
  setTimeout(() => { dialogNotice.value = {} }, 300)
}

function randomId(len = 5) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < len; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

function onSaveNotice() {
  const noticeDTO = {
    title: dialogNotice.value.title,
    content: dialogNotice.value.content,
    status: dialogNotice.value.status
  }
  if (dialogMode.value === 'add') {
    noticeDTO.id = randomId(5)
    noticeDTO.creatorId = '123'
    createNotice(noticeDTO).then(() => {
      closeDialog()
      fetchData()
    })
    return
  }
  noticeDTO.id = dialogNotice.value.id
  updateNotice(noticeDTO).then(() => {
    closeDialog()
    fetchData()
  })
}

function onEditNotice(notice) {
  dialogMode.value = 'edit'
  dialogNotice.value = { ...notice }
  dialog.value = true
}

function onDeleteNotice(notice) {
  // TODO: 删除公告逻辑
}

onMounted(fetchData)
</script>

<style scoped>
.full-width-card {
  width: 100% !important;
  margin: 0 !important;
  box-sizing: border-box;
}
.v-card-text {
  padding: 0 !important;
}
.v-btn {
  min-width: 80px;
}
.gap-btns > .v-btn + .v-btn {
  margin-left: 12px;
}
</style>
